﻿using System;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace ComicTool.Model
{
    public class ZipCompressedComic : Comic
    {
        public ZipCompressedComic(string name, LoadingStrategy strategy)
            : base(name, strategy)
        {
        }

        protected override void LoadFromStream(Stream stream)
        {
            ZipFile zf = null;
            try
            {
                List<Page> pages = new List<Page>();
                zf = new ZipFile(stream);
                foreach (ZipEntry entry in zf)
                {
                    if (entry.IsFile && entry.Name.IsValidExtension())
                    {
                        Page page = Page.CreatePage(stream, entry);
                        pages.Add(page);
                    }
                    else if (entry.Name.Equals("comicinfo.xml",
                            StringComparison.InvariantCultureIgnoreCase))
                    {
                        LoadComicInfo(zf.GetInputStream(entry));
                    }
                }
                pages.Sort();
                Utility.Dispatcher.BeginInvoke(() => Pages.AddRange(pages));
            }
            finally
            {
                zf.IsStreamOwner = false;
                zf.Close();
            }
        }

        protected override string Extension
        {
            get
            {
                return "cbz";
            }
        }

        protected override string Filter
        {
            get
            {
                return "CBZ files (*.cbz)|*.cbz|All files (*.*)|*.*";
            }
        }
    }
}
